package com.ch.ms.server.login.service.impl;


import com.ch.ms.data.domain.account.ChmsAccount;
import com.ch.ms.data.domain.character.ChmsCharacter;
import com.ch.ms.data.repository.account.ChmsAccountRepository;
import com.ch.ms.server.base.configuration.motan.MotanServiceExports;
import com.ch.ms.service.account.ChmsAccountService;
import com.weibo.api.motan.config.springsupport.annotation.MotanService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.transaction.Transactional;
import java.util.List;
import java.util.Objects;

@Service
@Slf4j
@Transactional
@MotanService(export = MotanServiceExports.CHMS_ACCOUNT_SERVICE)
public class ChmsAccountServiceImpl implements ChmsAccountService {

    private final ChmsAccountRepository repository;

    @Autowired
    public ChmsAccountServiceImpl(ChmsAccountRepository repository) {
        this.repository = repository;
    }


    public boolean login(String userName, String password) {
        log.info("账号{}正在尝试登录", userName);
        ChmsAccount account = repository.findByUserName(userName);

        if (Objects.isNull(account)) {
            log.error("账号不存在");
            return false;
        }


        if (!account.getPassword().trim().equals(password)) {

            log.error("密码不正确!");
            return false;
        }

        account.setLogged(true);
        repository.save(account);

        return true;
    }

    @Override
    public ChmsAccount findByUserName(String userName) {
        return repository.findByUserName(userName);
    }


    //FIXME 这里延迟加载没有执行sql,可能是直接从一级缓存中读取的数据,这会导致手动更新了数据但加载不出来
    //@Cacheable("books")
    @Override
    public List<ChmsCharacter> getCharacters(ChmsAccount account) {
        return account.getCharacters();
    }


}
